package com.wn.shiro;


import com.wn.entity.Manager;
import com.wn.entity.Permission;
import com.wn.service.ManagerService;
import com.wn.service.PermissionService;
import com.wn.service.RoleService;
import com.wn.utils.JWTUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

//自定义域
@Configuration
public class MyRealm extends AuthorizingRealm {
    @Autowired
    ManagerService managerService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    @Override
    public boolean supports(AuthenticationToken token) {
//        这里是shiro底层的问题，我们要手动重写底层的判断逻辑
        return token instanceof MyJsonWebToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //通过下面的认证方法SimpleAuthenticationInfo对象中的凭证获取到token的值！
        String token = principals.getPrimaryPrincipal()+"";
        String username = JWTUtils.getUsername(token);
        //使用username去数据库查出你的所有的角色和权限并封装到SimpleAuthorizationInfo
        //查询当前登录的subject用户的角色
        String roleName = roleService.findByAccount(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(roleName);
        //查询当前登录的subject的权限集合
        Set<String> perms = permissionService.findByAccount(username);
        simpleAuthorizationInfo.setStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken jwtToken) throws AuthenticationException {
        //通过token获取我们自定义的MyJsonWebToken中存入的token
        String token = jwtToken.getPrincipal()+"";

        //从token中拿出用户名 后面篡改token的body值，来尝试，看能够获取到username，不先校验的情况
        String username = JWTUtils.getUsername(token);
        if ("".equals(username)){
            throw new  AuthenticationException("用户信息错误");
        }
        //调用service，查询数据库，获取用户信息
        Manager user = managerService.findByUsername(username);
        boolean verify = JWTUtils.verify(token, username, user.getPassword());
        if (verify){//说明代码没有问题
           return new SimpleAuthenticationInfo(token,token,"myRealm");
        }
        return null;
    }
}
